/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package admin.util;

import java.util.concurrent.ConcurrentHashMap;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * @author Nothing4ever
 */
public class UtilEjb {

    public static UtilEjb getInstance() {
        return UtilEjbHolder.INSTANCE;
    }


    private Context context;
    private final ConcurrentHashMap<String, Object> ejbCaches;

    private UtilEjb() {
        initContext();
        ejbCaches = new ConcurrentHashMap<>(7);
    }

    private void initContext() {
        try {
            if (getContext() == null) {
                setContext(new InitialContext());
            }
        } catch (Exception e) {
            System.out.println("error of getContext !!");
            e.printStackTrace();
        }
        System.out.println("context obj    " + getContext());
    }

    private Object findEjb(String jndiName) throws NamingException {
        if (!ejbCaches.containsKey(jndiName)) {
            ejbCaches.put(jndiName, getContext().lookup(jndiName));
        }
        return ejbCaches.get(jndiName);
        //return context.lookup(jndiName);
    }

    public <T>T getEJB(String jndi) {
        try {
            return (T)findEjb(jndi);
        } catch (Exception e) {
            System.out.println("look up ejb is error !!!");
            e.printStackTrace();
        }
        return null;
    }

    protected void setContext(Context context) {
        this.context = context;
    }

    protected Context getContext() {
        return context;
    }

    private static class UtilEjbHolder {

        private static final UtilEjb INSTANCE = new UtilEjb();
    }
}
